<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span><i class="el-icon-document"></i> 设备详情信息</span>
      </div>

      <el-row>
        <el-col :span="24">
          <el-divider content-position="left"><h3>基本信息</h3></el-divider>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="detail-item">
                <div class="detail-label"><i class="el-icon-tickets"></i> 设备编码：</div>
                <div class="detail-value">{{ equipment.equipmentCode || "-" }}</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="detail-item">
                <div class="detail-label"><i class="el-icon-tickets"></i> 设备名称：</div>
                <div class="detail-value">{{ equipment.equipmentName || "-" }}</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="detail-item">
                <div class="detail-label"><i class="el-icon-office-building"></i> 设备类型：</div>
                <div class="detail-value">{{ equipment.equipmentTypeName || "-" }}</div>
              </div>
            </el-col>
          </el-row>

          <el-row :gutter="20" style="margin-top: 20px;">
            <el-col :span="8">
              <div class="detail-item">
                <div class="detail-label"><i class="el-icon-circle-check"></i> 设备状态：</div>
                <div class="detail-value">
                  <el-tag v-if="equipment.equipmentStatus === '0'" type="success">空闲</el-tag>
                  <el-tag v-else-if="equipment.equipmentStatus === '1'" type="warning">在用</el-tag>
                  <el-tag v-else-if="equipment.equipmentStatus === '2'" type="danger">维修中</el-tag>
                  <el-tag v-else-if="equipment.equipmentStatus === '3'" type="info">报废</el-tag>
                  <el-tag v-else type="warning">在用</el-tag>
                </div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="detail-item">
                <div class="detail-label"><i class="el-icon-location"></i> 所属车间：</div>
                <div class="detail-value">{{ equipment.workshopName || "-" }}</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="detail-item">
                <div class="detail-label"><i class="el-icon-office-building"></i> 所属生产线：</div>
                <div class="detail-value">{{ equipment.productionLineName || "-" }}</div>
              </div>
            </el-col>
          </el-row>
        </el-col>
      </el-row>

      <el-row style="margin-top: 30px;">
        <el-col :span="24">
          <el-divider content-position="left"><h3>规格信息</h3></el-divider>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="detail-item">
                <div class="detail-label"><i class="el-icon-info"></i> 设备型号：</div>
                <div class="detail-value">{{ equipment.model || "-" }}</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="detail-item">
                <div class="detail-label"><i class="el-icon-s-operation"></i> 规格：</div>
                <div class="detail-value">{{ equipment.specifications || equipment.specification || "-" }}</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="detail-item">
                <div class="detail-label"><i class="el-icon-s-shop"></i> 制造商：</div>
                <div class="detail-value">{{ equipment.manufacturer || "-" }}</div>
              </div>
            </el-col>
          </el-row>

          <el-row :gutter="20" style="margin-top: 20px;">
            <el-col :span="8">
              <div class="detail-item">
                <div class="detail-label"><i class="el-icon-date"></i> 采购日期：</div>
                <div class="detail-value">{{ parseTime(equipment.purchaseDate, '{y}-{m}-{d}') || "-" }}</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="detail-item">
                <div class="detail-label"><i class="el-icon-money"></i> 采购价格：</div>
                <div class="detail-value">{{ equipment.purchasePrice ? parseFloat(equipment.purchasePrice).toFixed(2) : "0.00" }} 元</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="detail-item">
                <div class="detail-label"><i class="el-icon-picture"></i> 设备图片：</div>
                <div class="detail-value equipment-image">
                  <img v-if="equipment.imageUrl" :src="equipment.imageUrl" alt="设备图片" class="equipment-img" @click="previewImage(equipment.imageUrl)">
                  <div v-else class="no-image">暂无图片</div>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-col>
      </el-row>

      <el-row style="margin-top: 30px;">
        <el-col :span="24">
          <el-divider content-position="left"><h3>管理与维护</h3></el-divider>
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="detail-item">
                <div class="detail-label"><i class="el-icon-user"></i> 负责人：</div>
                <div class="detail-value">{{ equipment.userNickName || equipment.responsiblePerson || "-" }}</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="detail-item">
                <div class="detail-label"><i class="el-icon-office-building"></i> 所属部门：</div>
                <div class="detail-value">{{ equipment.departmentName || "-" }}</div>
              </div>
            </el-col>
          </el-row>

          <el-row :gutter="20" style="margin-top: 20px;">
            <el-col :span="24">
              <div class="detail-item">
                <div class="detail-label"><i class="el-icon-notebook-2"></i> 备注：</div>
                <div class="detail-value">{{ equipment.remark || '-' }}</div>
              </div>
            </el-col>
          </el-row>
        </el-col>
      </el-row>

      <el-row style="margin-top: 30px;">
        <el-col :span="24">
          <el-divider content-position="left"><h3>记录与日志</h3></el-divider>
          <el-tabs v-model="activeTab" type="border-card">
            <el-tab-pane label="点检记录" name="inspection">
              <el-table
                v-loading="inspectionLoading"
                :data="inspectionRecords"
                style="width: 100%"
                border
                size="small"
                :header-cell-style="{background:'#f8f8f9',color:'#606266'}"
              >
                <el-table-column prop="recordCode" label="记录编号" width="180" />
                <el-table-column prop="inspectionTime" label="点检时间" width="180">
                  <template slot-scope="scope">{{ parseTime(scope.row.inspectionTime) }}</template>
                </el-table-column>
                <el-table-column prop="inspectionPerson" label="点检人员" />
                <el-table-column prop="status" label="点检结果">
                  <template slot-scope="scope">
                    <el-tag :type="scope.row.status === 'pass' ? 'success' : 'danger'">
                      {{ scope.row.status === 'pass' ? '合格' : '不合格' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="remark" label="备注" />
                <el-table-column label="操作" width="150" align="center">
                  <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-view" @click="viewInspectionDetail(scope.row)">查看详情</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <pagination
                v-if="inspectionTotal > 0"
                :total="inspectionTotal"
                :page.sync="inspectionQuery.pageNum"
                :limit.sync="inspectionQuery.pageSize"
                @pagination="getInspectionRecords"
              />
              <div v-else class="empty-block">暂无数据</div>
            </el-tab-pane>
            
            <el-tab-pane label="保养记录" name="maintenance">
              <el-table
                v-loading="maintenanceLoading"
                :data="maintenanceRecords"
                style="width: 100%"
                border
                size="small"
                :header-cell-style="{background:'#f8f8f9',color:'#606266'}"
              >
                <el-table-column prop="orderCode" label="工单编号" width="180" />
                <el-table-column prop="maintenanceTime" label="保养时间" width="180">
                  <template slot-scope="scope">{{ parseTime(scope.row.maintenanceTime) }}</template>
                </el-table-column>
                <el-table-column prop="maintenancePerson" label="保养人员" />
                <el-table-column prop="maintenanceType" label="保养类型">
                  <template slot-scope="scope">
                    <el-tag :type="getMaintenanceTypeTag(scope.row.maintenanceType)">
                      {{ getMaintenanceTypeText(scope.row.maintenanceType) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="status" label="完成状态">
                  <template slot-scope="scope">
                    <el-tag :type="scope.row.status === 'completed' ? 'success' : 'info'">
                      {{ scope.row.status === 'completed' ? '已完成' : '进行中' }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="150" align="center">
                  <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-view" @click="viewMaintenanceDetail(scope.row)">查看详情</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <pagination
                v-if="maintenanceTotal > 0"
                :total="maintenanceTotal"
                :page.sync="maintenanceQuery.pageNum"
                :limit.sync="maintenanceQuery.pageSize"
                @pagination="getMaintenanceRecords"
              />
              <div v-else class="empty-block">暂无数据</div>
            </el-tab-pane>
            
            <el-tab-pane label="维修记录" name="repair">
              <el-table
                v-loading="repairLoading"
                :data="repairRecords"
                style="width: 100%"
                border
                size="small"
                :header-cell-style="{background:'#f8f8f9',color:'#606266'}"
              >
                <el-table-column prop="orderCode" label="工单编号" width="180" />
                <el-table-column prop="repairTime" label="维修时间" width="180">
                  <template slot-scope="scope">{{ parseTime(scope.row.repairTime) }}</template>
                </el-table-column>
                <el-table-column prop="repairPerson" label="维修人员" />
                <el-table-column prop="faultType" label="故障类型" />
                <el-table-column prop="status" label="维修状态">
                  <template slot-scope="scope">
                    <el-tag :type="getRepairStatusTag(scope.row.status)">
                      {{ getRepairStatusText(scope.row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="150" align="center">
                  <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-view" @click="viewRepairDetail(scope.row)">查看详情</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <pagination
                v-if="repairTotal > 0"
                :total="repairTotal"
                :page.sync="repairQuery.pageNum"
                :limit.sync="repairQuery.pageSize"
                @pagination="getRepairRecords"
              />
              <div v-else class="empty-block">暂无数据</div>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>

      <el-row style="margin-top: 30px;">
        <el-col :span="24" style="text-align: center;">
          <el-button type="primary" icon="el-icon-back" @click="goBack">返回列表</el-button>
        </el-col>
      </el-row>
    </el-card>
    <!-- 图片预览对话框 -->
    <el-dialog :visible.sync="imagePreviewVisible" append-to-body width="60%" center>
      <img :src="previewImageUrl" alt="" style="max-width: 100%; max-height: 70vh; display: block; margin: 0 auto;">
    </el-dialog>
  </div>
</template>

<script>
import { getEquipment, getEquipmentInspectionRecords, getEquipmentMaintenanceRecords, getEquipmentRepairRecords } from "@/api/sb/equipmentLedger";
import { parseTime } from '@/utils/ruoyi';
import Pagination from "@/components/Pagination";

export default {
  name: "EquipmentLedgerDetail",
  components: {
    Pagination
  },
  data() {
    return {
      equipmentId: null,
      equipment: {
        equipmentCode: '',
        equipmentName: '',
        equipmentTypeId: null,
        equipmentTypeName: '',
        equipmentStatus: '',
        workshopName: '',
        productionLineName: '', 
        departmentName: '',
        model: '',
        specifications: '',
        specification: '',
        manufacturer: '',
        purchaseDate: '',
        purchasePrice: 0,
        imageUrl: '',
        responsiblePerson: '',
        userNickName: '',
        remark: ''
      },
      imagePreviewVisible: false,
      previewImageUrl: '',
      
      // 标签页相关
      activeTab: 'inspection',
      
      // 点检记录相关
      inspectionRecords: [],
      inspectionTotal: 0,
      inspectionLoading: false,
      inspectionQuery: {
        pageNum: 1,
        pageSize: 10
      },
      
      // 保养记录相关
      maintenanceRecords: [],
      maintenanceTotal: 0,
      maintenanceLoading: false,
      maintenanceQuery: {
        pageNum: 1,
        pageSize: 10
      },
      
      // 维修记录相关
      repairRecords: [],
      repairTotal: 0,
      repairLoading: false,
      repairQuery: {
        pageNum: 1,
        pageSize: 10
      }
    };
  },
  created() {
    this.equipmentId = this.$route.params.id;
    this.getEquipmentDetail();
  },
  mounted() {
    // 初始加载点检记录
    this.getInspectionRecords();
  },
  watch: {
    'equipment.contactPhone': {
      handler(newVal) {
        this.maskPhone(newVal);
      },
      immediate: true
    },
    activeTab: {
      handler(newTab) {
        // 切换标签页时加载对应数据
        if (newTab === 'inspection') {
          this.getInspectionRecords();
        } else if (newTab === 'maintenance') {
          this.getMaintenanceRecords();
        } else if (newTab === 'repair') {
          this.getRepairRecords();
        }
      }
    }
  },
  methods: {
    parseTime,
    // 获取设备详情
    getEquipmentDetail() {
      getEquipment(this.equipmentId).then(response => {
        console.log("设备详情数据:", response.data);
        this.equipment = response.data;
        
        // 确保图片URL路径正确
        if (this.equipment.imageUrl && !this.equipment.imageUrl.startsWith('http') && !this.equipment.imageUrl.startsWith('/')) {
          this.equipment.imageUrl = process.env.VUE_APP_BASE_API + this.equipment.imageUrl;
        }
      });
    },
    // 掩码电话号码
    maskPhone(phone) {
      if (!phone) {
        this.maskedPhone = '-';
        return;
      }
      
      // 处理不同长度的电话号码
      if (phone.length <= 7) {
        // 短号码，只隐藏中间部分
        this.maskedPhone = phone.replace(/(\d{2})\d+(\d{2})/, '$1****$2');
      } else if (phone.length <= 11) {
        // 标准手机号
        this.maskedPhone = phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
      } else {
        // 更长的号码
        this.maskedPhone = phone.replace(/(\d{4})\d{4}(\d+)/, '$1****$2');
      }
    },
    // 返回列表
    goBack() {
      this.$router.push({ path: "/sb/equipment-ledger" });
    },
    
    // 获取点检记录
    getInspectionRecords() {
      if (!this.equipmentId) return;
      
      this.inspectionLoading = true;
      getEquipmentInspectionRecords(this.equipmentId, this.inspectionQuery)
        .then(response => {
          console.log('点检记录:', response);
          if (response.code === 200) {
            // 如果后端返回的是数组直接使用，否则尝试从response.rows或response.data获取
            if (Array.isArray(response.rows)) {
              this.inspectionRecords = response.rows;
              this.inspectionTotal = response.total || response.rows.length;
            } else if (Array.isArray(response.data)) {
              this.inspectionRecords = response.data;
              this.inspectionTotal = response.total || response.data.length;
            } else {
              // 没有数据
              this.inspectionRecords = [];
              this.inspectionTotal = 0;
            }
          } else {
            // 没有数据
            this.inspectionRecords = [];
            this.inspectionTotal = 0;
          }
        })
        .catch(error => {
          console.error('获取点检记录失败:', error);
          this.inspectionRecords = [];
          this.inspectionTotal = 0;
        })
        .finally(() => {
          this.inspectionLoading = false;
        });
    },
    
    // 获取保养记录
    getMaintenanceRecords() {
      if (!this.equipmentId) return;
      
      this.maintenanceLoading = true;
      getEquipmentMaintenanceRecords(this.equipmentId, this.maintenanceQuery)
        .then(response => {
          console.log('保养记录:', response);
          if (response.code === 200) {
            // 如果后端返回的是数组直接使用，否则尝试从response.rows或response.data获取
            if (Array.isArray(response.rows)) {
              this.maintenanceRecords = response.rows;
              this.maintenanceTotal = response.total || response.rows.length;
            } else if (Array.isArray(response.data)) {
              this.maintenanceRecords = response.data;
              this.maintenanceTotal = response.total || response.data.length;
            } else {
              // 没有数据
              this.maintenanceRecords = [];
              this.maintenanceTotal = 0;
            }
          } else {
            // 没有数据
            this.maintenanceRecords = [];
            this.maintenanceTotal = 0;
          }
        })
        .catch(error => {
          console.error('获取保养记录失败:', error);
          this.maintenanceRecords = [];
          this.maintenanceTotal = 0;
        })
        .finally(() => {
          this.maintenanceLoading = false;
        });
    },
    
    // 获取维修记录
    getRepairRecords() {
      if (!this.equipmentId) return;
      
      this.repairLoading = true;
      getEquipmentRepairRecords(this.equipmentId, this.repairQuery)
        .then(response => {
          console.log('维修记录:', response);
          if (response.code === 200) {
            // 如果后端返回的是数组直接使用，否则尝试从response.rows或response.data获取
            if (Array.isArray(response.rows)) {
              this.repairRecords = response.rows;
              this.repairTotal = response.total || response.rows.length;
            } else if (Array.isArray(response.data)) {
              this.repairRecords = response.data;
              this.repairTotal = response.total || response.data.length;
            } else {
              // 没有数据
              this.repairRecords = [];
              this.repairTotal = 0;
            }
          } else {
            // 没有数据
            this.repairRecords = [];
            this.repairTotal = 0;
          }
        })
        .catch(error => {
          console.error('获取维修记录失败:', error);
          this.repairRecords = [];
          this.repairTotal = 0;
        })
        .finally(() => {
          this.repairLoading = false;
        });
    },
    
    // 查看点检详情
    viewInspectionDetail(row) {
      this.$router.push({ 
        path: `/sb/inspection-record/detail/${row.id || row.recordId}`,
        query: { from: 'equipment', equipmentId: this.equipmentId }
      });
    },
    
    // 查看保养详情
    viewMaintenanceDetail(row) {
      this.$router.push({ 
        path: `/sb/maintenance-order/detail/${row.id || row.orderId}`,
        query: { from: 'equipment', equipmentId: this.equipmentId }
      });
    },
    
    // 查看维修详情
    viewRepairDetail(row) {
      this.$router.push({ 
        path: `/sb/repair-order/detail/${row.id || row.orderId}`,
        query: { from: 'equipment', equipmentId: this.equipmentId }
      });
    },
    
    // 获取保养类型标签样式
    getMaintenanceTypeTag(type) {
      const typeMap = {
        'daily': 'info',
        'weekly': 'success',
        'monthly': 'warning',
        'quarterly': 'danger',
        'yearly': 'primary'
      };
      return typeMap[type] || 'info';
    },
    
    // 获取保养类型文本
    getMaintenanceTypeText(type) {
      const typeMap = {
        'daily': '日常保养',
        'weekly': '周保养',
        'monthly': '月保养',
        'quarterly': '季度保养',
        'yearly': '年度保养'
      };
      return typeMap[type] || '其他保养';
    },
    
    // 获取维修状态标签样式
    getRepairStatusTag(status) {
      const statusMap = {
        'pending': 'info',
        'processing': 'warning',
        'completed': 'success',
        'failed': 'danger'
      };
      return statusMap[status] || 'info';
    },
    
    // 获取维修状态文本
    getRepairStatusText(status) {
      const statusMap = {
        'pending': '待处理',
        'processing': '处理中',
        'completed': '已完成',
        'failed': '处理失败'
      };
      return statusMap[status] || '未知状态';
    },
    
    // 预览图片
    previewImage(url) {
      if (!url) return;
      
      // 创建一个新窗口或对话框来预览图片
      const h = this.$createElement;
      
      this.$msgbox({
        title: '设备图片预览',
        message: h('div', { style: 'text-align: center;' }, [
          h('img', {
            attrs: { src: url, alt: '设备图片' },
            style: 'max-width: 100%; max-height: 500px;'
          })
        ]),
        showCancelButton: false,
        confirmButtonText: '关闭',
        center: true,
        customClass: 'image-preview-dialog'
      }).catch(() => {});
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.detail-title {
  border-bottom: 2px solid #f0f0f0;
  padding-bottom: 10px;
  margin-bottom: 20px;
}

.detail-item {
  margin-bottom: 10px;
}

.detail-label {
  font-weight: bold;
  margin-bottom: 5px;
  color: #606266;
}

.detail-value {
  color: #333;
}

.equipment-image {
  display: flex;
  align-items: center;
  justify-content: flex-start;
}

.equipment-img {
  max-width: 100px;
  max-height: 100px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid #e1e1e1;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.equipment-img:hover {
  transform: scale(1.05);
  box-shadow: 0 2px 15px 0 rgba(0, 0, 0, 0.2);
}

.no-image {
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  background-color: #f5f7fa;
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  color: #909399;
}

.image-preview-dialog .el-message-box__message {
  max-height: 500px;
  overflow: auto;
}

.phone-container {
  display: flex;
  align-items: center;
}

.phone-eye {
  margin-left: 10px;
  color: #409EFF;
  cursor: pointer;
}

.card-subtitle {
  font-size: 16px;
  margin: 10px 0;
  padding-left: 10px;
  border-left: 4px solid #409EFF;
  line-height: 20px;
}

.log-item {
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.log-meta {
  display: flex;
  justify-content: space-between;
}
</style> 